package top.huhuiyu.study.servlet.user;

import top.huhuiyu.study.dao.TbUserDAO;
import top.huhuiyu.study.entity.Result;
import top.huhuiyu.study.entity.TbUser;
import top.huhuiyu.study.util.JsonUtils;
import top.huhuiyu.study.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet", urlPatterns = "/user/login.action")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        try {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            // 参数非空校验
            if (StringUtil.isBlank(username)) {
                Result<String> result = Result.fail("用户名不能为空", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            if (StringUtil.isBlank(password)) {
                Result<String> result = Result.fail("密码不能为空", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            // 查询用户名是否存在
            TbUser check = TbUserDAO.queryByName(username);
            if (check == null) {
                Result<String> result = Result.fail("用户名不存在", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            // 判断密码是否正确
            if(password.equalsIgnoreCase(check.getPassword())) {
                Result<String> result = Result.success("登录成功", null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            Result<String> result = Result.fail("密码错误", null);
            writer.println(JsonUtils.stringify(result));

        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("登录发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }
}
